I was trying to access http://localhost/Reports/Page.aspx, in other words an ASP.Net page in the Reports path of the local site. Instead, I was getting a Windows authentication prompt that had no business being there. At first I thought to debug the page, but it wouldn't even get there before I got the authentication prompt. I googled for it, but I didn't get far because I was looking for weird Windows authentication prompts, not for the specific location of my page: the Reports folder. It was stranger yet, as I stopped IIS and the authentication dialog was still appearing!

In the end, a colleague told me the solution: SQL Reporting Services is answering on the local Reports path! I stopped the service and voila! no more authentication prompt. Instead, a Service unavailable 503 error. This article explained things quite clearly. Even if you stop the service, you have to delete the access control list entry for /Reports with the command netsh http delete urlacl url=http://+:80/Reports or, I guess, restart the system after you set the Reporting Services service to Manual or Disabled.

Update: It is even easier to go to Sql Server Configuration Tools (in the Start Menu), run the Reporting Service Configuration Manager, then change the URL for the Report Manager URL to something other than Reports.

But what is this strange Access Control List? You can get a clue by reading about Http.sys API in Windows Vista and above and about Namespace Reservation. Apparently, one can do similar things on Windows Server 2003 and maybe even XP with the Httpcfg utility.

Short version: open registry, look for file association entry, locate the command subkey and check if, besides the (Default) value, there isn't a command multistring value that looks garbled. Rename or remove it.

Now for the long version. I've had this problem for a long time now: trying to open an Office doc file by double clicking it or selecting "Open" from the context menu or even trying "Open with" and selecting WinWord.exe threw an error that read like this: This action is only valid for installed products. This was strange, as I had Office 2007 installed and I could open Word just fine and open a document from within; it only had problems with the open command.

As I am rarely using Office at home, I didn't deem it necessary to solve the problem, but this morning I've decided that it is a matter of pride to make it work. After all, I have an IT blog and readers look up to me for technical advice. Both of them. So away I go to try to solve the problem.

The above error message is so looked up that it came up in Google autocomplete, but the circumstances and possible solutions are so varied that it didn't help much. I did find an article that explained how Office actually opens up documents. It said to go in the registry and look in the HKEY_CLASSES_ROOT\Word.Document.12\shell\Open\command subkey. There should be a command line that looks like "C:\Program Files\Microsoft Office\Office12\WINWORD.EXE" /n /dde. The /dde flag is an internal undocumented flag that tells Windows to use the Dynamic Data Exchange server to communicate the command line arguments to Word, via the next key in the registry: HKEY_CLASSES_ROOT\Word.Document.12\shell\Open\ddeexec which looks like: [REM _DDE_Direct][FileOpen("%1")]. So in other words (pun not intended) WinWord should open up with the /n flag, which instructs to start with no document open, then execute the FileOpen command with the file provided. If I had this as the value of the command registry key, it should work.

Ok, opened up the registry editor (if you don't know what that is or how to use it, it is my recommendation to NOT use it. instead ask a friend who knows what to do. You've been warned!), went to where the going is good and found the command subkey. It held a (Default) value that looked like it should and then it held another value named also command, only this one was not a string (REG_SZ), but a multi string (REG_MULTI_SZ), and its value was something like C84DVn-}f(YR]eAR6.jiWORDFiles>L&rfUmW.cG.e%fI4G}jd /n /dde. Do not worry, there is nothing wrong with your monitor, I control the horizontal, vertical and diagonal, it looked just as weird as you see it. At first I thought it was some weird check mechanism, some partial hash or weird encoding method used in that weird REG_MULTI_SZ type, which at the moment I didn't know what it meant. Did I mention it was weird? Well, it turns out that a multi string key is a list of strings, not a single line string, so there was no reason for the weirdness at all. You can see that it was expecting a list of strings because when you modify the key it presents you with a multiline textbox, not a singleline one.

So, thank you for reading thus far, the solution was: remove all the annoying command values (NOT the command subkeys) leaving the (Default) to its normal state. I do not know what garbled the registry, but what happened is that Windows was trying to execute the strange string and, obviously, failed. The obscure error message was basically saying that it didn't find the file or command you were trying to execute and has nothing to do with Office per se.

Of course,you have to repeat the procedure for all the file types that are affected, like RTF, for example.


Today I've released version 1.2 of the HotBabe.NET application. It is a program that stays in the traybar, showing a transparent picture, originally of a woman, sitting on top of your other applications. Clicks go through the image and the opacity of the picture is set so that it doesn't bother the use of the computer. When the CPU use or the memory use or other custom measurements change, the image changes as well. The original would show a girl getting naked as the use of CPU went up. Since I couldn't use what images it should use, I did my own program in .NET. This blog post is about what I have learned about Windows Forms while creating this application.

Step 1: Making the form transparent



Making a Windows Form transparent is not as simple as setting the background transparent. It needs to have:
  • FormBorderStyle = FormBorderStyle.None
  • AllowTransparency = true
  • TransparencyKey = BackColor
However, when changing the Opacity of the form, I noticed that the background color would start showing! The solution for this is to set the BackColor to Color.White, as White is not affected by opacity when set as TransparencyKey, for some reason.

Step 2: Making the form stay on top all other windows



That is relatively easy. Set TopMost = true. You have to set it to true the first time, during load, otherwise you won't be able to set it later on. I don't know why, it just happened.

Update: I noticed that, even when TopMost was set, the image would vanish beneath other windows. I've doubled the property with setting WS_EX_TopMost on the params ExStyle (see step 4).

Step 3: Show the application icon in the traybar and hide the taskbar



Hiding the taskbar is as easy as ShowInTaskbar = false and putting a notification icon in the traybar is simple as well:
_icon = new NotifyIcon(new Container())
{
Visible = true
};
Set the ContextMenu to _icon and you have a tray icon with a menu. There is a catch, though. A NotifyIcon control needs an Icon, an image of a certain format. My solution was, instead of bundling an icon especially for this, to convert the main girl image into an icon, so I used this code.

Step 4: Hide the application from Alt-Tab, make it not get focus and make it so that the mouse clicks through



In order to do that, something must be done at the PInvoke level, in other words, using unsafe system libraries. At first I found out that I need to change a flag value which can be read and written to using GetWindowLong and SetWindowLong from user32.dll. I needed to set the window style with the following attributes:
WS_EX_Layered (Windows Xp/2000+ layered window)
WS_EX_Transparent (Allows the windows to be transparent to the mouse)
WS_EX_ToolWindow (declares the window as a tool window, therefore it does not appear in the Alt-Tab application list)
WS_EX_NoActivate (Windows 2000/XP: A top-level window created with this style does not become the foreground window when the user clicks it).

Then I found out that Form has a virtual method called CreateParams giving me access to the style flag value. Here is the complete code:
protected override CreateParams CreateParams
{
get
{
CreateParams ws = base.CreateParams;

if (ClickThrough)
{
ws.ExStyle |= UnsafeNativeMethods.WS_EX_Layered;
ws.ExStyle |= UnsafeNativeMethods.WS_EX_Transparent;
}
// do not show in Alt-tab
ws.ExStyle |= UnsafeNativeMethods.WS_EX_ToolWindow;
// do not make foreground window
ws.ExStyle |= UnsafeNativeMethods.WS_EX_NoActivate;
return ws;
}
}


However, the problem was that if I changed ClickThrough, it didn't seem to do anything. It was set once and that was it. I noticed that changing Opacity would also set the click through style, so I Reflector-ed the System.Windows.Forms.dll and looked in the source of Opacity. Something called UpdateStyles was used (This method calls the CreateParams method to get the styles to apply) so I used it.

Update: Apparently, the no activate behaviour can also be set by overriding ShowWithoutActivation and returning true. I've set it, too, just to be sure.

Step 5: Now that the form is transparent and has no border or control box, I can't move the window around. I need to make it draggable from anywhere



There is no escape from native methods this time:
private void mainMouseDown(object sender, MouseEventArgs e)
{
// Draggable from anywhere
if (e.Button == MouseButtons.Left)
{
UnsafeNativeMethods.ReleaseCapture();
UnsafeNativeMethods.SendMessage(Handle,
UnsafeNativeMethods.WM_NCLBUTTONDOWN,
UnsafeNativeMethods.HT_CAPTION, 0);
}
}
Both ReleaseCapture and SendMessage are user32.dll functions. What this mouse down event handler does is say to the Window that no matter where it was clicked, it actually clicked the draggable area.

Step 6: Remove flicker



Well, I am getting a bit ahead of myself, here, the flickering becomes annoying only when I implement the blending of an image into another, but since it is also a style setting, I am putting it here:
SetStyle(ControlStyles.AllPaintingInWmPaint 
| ControlStyles.UserPaint
| ControlStyles.OptimizedDoubleBuffer, true);
This piece of code, placed in the Form constructor, tells the form to use a double buffer for drawing and to not clear the form before drawing something else.

Update: It seems the same thing can be achieved by setting the Control property DoubleBuffer to true as it seems to be setting ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint and ControlStyles.UserPaint seems to be set by default.

Step 7: Blend the images one into the other



Well, in order to make an image blend nicely into the next, I used a Timer. 10 times a second I would decrease the opacity of the first, increase the opacity of the second and draw them one over the other.

A small detour: if you think about it, this is not absolutely correct. A 70% opacity pixel blocks 70% of the light and lets 30% of the image behind show. If the image underneath has 30% opacity, then it shows 30% left from 30% of the image and it doesn't get opaque. But if I just set the opacity of the bakground image to 100%, it shows really strong on the parts of the images that are not overlapping, where image1 is transparent and image2 is not.

Unfortunately there is no resource friendly way to read write/pixels. It's either GetPixel/SetPixel in a Bitmap class (which are very slow) or using pinvoke again. I prefered to use the opacity hack which looks ok.

I was already using an extension method to invoke any change on the form on its own thread (as the Timer ran on its own thread and I would have gotten the "Cross-thread operation not valid: Control [...] accessed from a thread other than the thread it was created on" exception or "Invoke or BeginInvoke cannot be called on a control until the window handle has been created"):
public static void SafeInvoke(this Control control, Action action)
{
if (control.IsDisposed)
{
return;
}
if (!control.IsHandleCreated)
{
try
{
action();
}
catch (InvalidOperationException ex)
{
}
return;
}
if (control.InvokeRequired)
{
control.BeginInvoke(action);
}
else
{
action();
}
}

This is where I got the "Object is currently in use elsewhere" InvalidOperationException. Apparently the Image class is not thread-safe, so both the timer and the form were trying to access it. I tried locking the setter and getter of the Image property on the class responsible with the image blending effect, with no real effect. Strangely enough, the only solution was to Clone the image when I move it around. I am still looking for a solution that makes sense!

Step 8: Showing the window while dragging it



Using WS_EX_NOACTIVATE was great, but there is a minor inconvenience when trying to move the form around. Not only that the image is not shown while moving the form (On my computer it is set to not show the window contents while dragging it), but the rectangular hint that normally shows is not displayed either. The only way to know where your image ended up was to release the mouse button.

It appears that fixing this is not so easy as it seems. One needs to override WndProc and handle the WM_MOVING message. While handling it, a manual redraw of the form must be initiated via the user32.dll SetWindowPos method.

The nice part is that in this method you can actually specify how you want the form draw. I have chosen SWP_NoActivate, SWP_ShowWindow and SWP_NoSendChanging as flags, where NoActivate is similar with the exstyle flag, ShowWindow shows the entire form (not only the rectangle hint) and NoSendChanging seems to improve the movement smoothness.

Quirky enough, if I start the application without Click through set, then the rectangle hint DOES appear while dragging the window. And with my fix, both the image and the rectangle are shown, but not at the same time. It is a funny effect I don't know how to fix and I thought it was strange enough to not bother me: the rectangle is trying to keep up with the hot babe and never catches on :)

Step 9: Dragging custom images



I am a programmer, that means that it is likely to add too many features in my creations and never make any money out of them. That's why I've decided to add a new feature to HotBabe.NET: droppping your own images on it to display over your applications.

At first I have solved this via ExStyle, where a flag tells Windows the form accepts files dragged over it. A WndProc override handling the WM_DROPFILES message would do the rest. But then I've learned that Windows Forms have their own mechanism for handling file drops.

Here are the steps. First set AllowDrop to true. Then handle the DragEnter and DragDrop events. In my implementation I am checking that only one file is being dropped and that the file itself can be converted into an image BEFORE I display the mouse cursor hint telling the user a drop is allowed. That pretty much makes the ugly MessageBox that I was showing in the previous implementation unnecessary.

Step 10: Reading files from web, FTP, network, zip files, everywhere, with a single API



Reading and writing files is easy when working with local files, using System.IO classes, but when you want to expand to other sources, like web images or files bundles in archives, you get stuck. Luckily there is a general API for reading files using URI syntax in the System.Net.WebRequest class. Here is a sample code for reading any file that can be represented as an URI:
WebRequest req = WebRequest.Create(uriString);
using (var resp = req.GetResponse())
{
using(var stream= resp.GetResponseStream())
{
// do something with stream
}
}


WebRequest can also register your own classes for specific schemas, others than http, ftp, file, etc. I created my own handler for "zip:" URIs and now I can use the same code to read files, web resources of zipped files.

One point that needs clarification is that at first I wanted an URI of the format "zip://archive/file" and I got stuck when the host part of the URI, mainly the archive name, would not accept spaces in it. Instead use this format "schema:///whatever" (three slashes). This is a valid URI in any situation, as the host is empty and does not need to be validated in any way.

The rest are details and you can download the source of HotBabe.NET and see the exact implementation. Please let me know what you think and of any improvement you can imagine.

I was using these GIF images stored as embedded resources and suddenly I got an Out of memory exception from a component that I had no control over. All images were icon size, 16x16 or a little more, so a lot of the explanations for the error based on "you don't have enough memory!" (duh!) were not helpful. The images did have transparent pixels, and my gut feeling is that it all came from there.

I still don't know what caused it, but I did find a solution. Where I get the image I add an additional
image = image.GetThumbnailImage(image.Width, image.Height, null, IntPtr.Zero);
I know it's not something very intuitive, but it solved the problem.

The only significant difference between the image before and after the thumbnailization is the PixelFormat property that changed from PixelFormat.Format8bppIndexed to PixelFormat.Format32bppArgb.

The stack looks like this:
   at System.Drawing.Graphics.CheckErrorStatus(Int32 status)
at System.Drawing.Graphics.DrawImage(Image image, Rectangle destRect, Int32 srcX, Int32 srcY, Int32 srcWidth, Int32 srcHeight, GraphicsUnit srcUnit, ImageAttributes imageAttrs, DrawImageAbort callback, IntPtr callbackData)
at System.Drawing.Graphics.DrawImage(Image image, Rectangle destRect, Int32 srcX, Int32 srcY, Int32 srcWidth, Int32 srcHeight, GraphicsUnit srcUnit, ImageAttributes imageAttr, DrawImageAbort callback)
at System.Drawing.Graphics.DrawImage(Image image, Rectangle destRect, Int32 srcX, Int32 srcY, Int32 srcWidth, Int32 srcHeight, GraphicsUnit srcUnit, ImageAttributes imageAttr)


And, using Reflector, I could go as far as pinpointing the error to the method System.Drawing.SafeNativeMethods.Gdip.GdipDrawImageRectRectI which wraps the gdiplus.dll GdipDrawImageRectRectI function. It returns error status 3, which is Out of memory, and that is that. I couldn't find a C++ code for the GdiPlus library and even if I had, who I am kidding? :)

and has 4 comments
I was installing a Visual Studio project made by a very cool team and, as they are very cool, it had this very complex folder structure for every little class and test and long names on the folder and so on and so on. Therefore, when trying to create a file on my Windows XP computer, the installer of the project failed with the strange error: 'the file name you specified is not valid or too long'.

I was under the impression that the path was no longer limited to 255 characters in Windows XP, but I was wrong. The MAX_PATH constant in Windows XP is 260. Everything over that causes an error unless specifically using a UNC formatted path (starting with \\?\). Weird huh?

Here is a technical description of the path concept in Windows: File Names, Paths, and Namespaces.
And here is the KB article with the "solutions": You cannot delete a file or a folder on an NTFS file system volume.

Scripting Center
Download details: Scriptomatic 2.0

WMI or Windows Management Instrumentation is Windows service who's basic function if to get information from a computer (even remote ones), but that has been upgraded to be able to also put information or run stuff. Weird little things like the manufacturer of the sound card or information about installed and running programs can be extracted with WMI, but also reading from a database or automate Sysadmin tasks for all the computers in the network, etc.

Well, this blog entry is not supposed to explain what WMI is, but to introduce the Microsoft Scripting Center. The link is above, it shows you how you can access and display/modify, etc information with WMI using scripts. The tool Scriptomatic 2.0 (download link above) automatically creates scripts in vbs, js, python and perl to list information in any of the WMI classes. The Scripting Center has a lot of scripts, categorised, so that you can download them and use them directly or with little modification, also tutorials and other useful links. Check it out!

I had problems with WindowsFormsParkingWindow and a lot of the references on the web pointed to this blog article. Unfortunately, the page was not available when I started searching for it. The only place I could find it was google cache, god bless their big googly hearts :) Therefore I am reprinting the content here, maybe it helps people:

=== WindowsFormsParkingWindow a.k.a The devil ===

I have been working on an application for a few weeks and suddenly it started freezing up for no reason. After copious amounts of swearing and breaking keyboards I found a hidden window in the windows task list. It was called - WindowsFormsParkingWindow. My new worst nightmare.

Nothing seemed to stop this issue from killing my program. After more swearing and cursing I found that this error happened after ALT-Tabbing away from my app and back into it. The parking window would appear and my app would die. I ran WinSpy++ and made the hidden window visible. Behold the glory of the following...

The hidden window contained a user control that I had previously removed off the form. This might not make sense to you now but let me explain the significance. When you remove a control from a form/panel, it gets put onto a WindowsFormsParkingWindow until you put it back onto the panel/form. So the WindowsFormsParkingWindow is kind of like an intermediate place windows keeps user controls before they are put into containers.

You might ask now - "What has that got to do with my app freezing?" Well, I'll tell you exactly why... Because when you remove a control from a panel/form and it has focus, the focus stays on the control (which is now on an invisible form). That's why events fail to fire and the app becomes unresponsive.

The solution? Easy...

Instead of using pnlParent.Clear() or just removing the control you need to do the following:

1. Remove the focus from the current user control by setting it to the parent form.
2. Remove the desired user control by using the ParentControl.RemoveAt( indexOfUsercontrol )

This should clear up the issue.

I had to do this Export functionality that saves data in a file from the database after filtering by date. My first idea was "let's just export everything and only use an OpenFileDialog", but then the date filtering request came. I thought that changing the OpenFileDialog to add two date
time pickers would be an easy job, but, alas, it is close to impossible.

Good research came out of this, though:
FileDialogExtender - Customize a dialog by issuing API Messages to already open windows
Customize Your Open File Dialog - Customize a dialog by changing the registry
Advanced MessageBoxing with the C# MessageBoxIndirect Wrapper - a friendly C# wrapper class for the MessageBoxIndirect API that allows you to add a help button, custom icon, locale-aware buttons, and different modalities to a message box.
Control.WndProc Method - MSDN WndProc method